package com.Shoping.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("*.do")
public class EncodingFilter implements Filter {

    //字符编码（参数初始化）
    protected String encoding=null;
    //FilterConfig对象
    protected FilterConfig filterConfig=null;
    //初始化方法
    public void init(FilterConfig filterConfig) throws ServletException{
        //对filterConfig赋值
        this.filterConfig=filterConfig;
        //对初始化参数赋值
        this.encoding=filterConfig.getInitParameter("encoding");
    }

    //过滤器处理方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException
    {
        //判断字符是否有效
        if(encoding!=null)
        {
            //设置request字符编码
            servletRequest.setCharacterEncoding(encoding);
            //设置response字符编码
            servletResponse.setContentType("application/json;charset="+encoding);
        }
        //传递给下一过滤器
        filterChain.doFilter(servletRequest,servletResponse);
    }

    //销毁方法
    @Override
    public void destroy() {
        //释放资源
        this.encoding=null;
        this.filterConfig=null;
    }

}
